<template>
    <div>
        <el-card shadow="always" :body-style="{ padding: '20px' }">
            <template #header>
                <el-button
                    type="primary"
                    icon="ele-Plus"
                    @click="addTrademark"
                    v-has="'btn.Trademark.add'"
                    >添加</el-button
                >
            </template>
            <!-- card body -->
            <el-table :data="tabelData" border stripe>
                <el-table-column type="index" width="80" label="序号" align="center" />
                <el-table-column label="品牌名称" prop="tmName" align="center"/>
                <el-table-column label="品牌logo" prop="logoUrl" align="center">
                    <!-- 表格作用域插槽的作用域数据row代表当前行完整数据 $index代表当前数据的下标 -->
                    <template v-slot="{ row }">
                        <el-image
                            style="height: 100px"
                            :src="row.logoUrl"
                            fit="fill"
                            :lazy="true"
                            :preview-src-list="[row.logoUrl]"
                            :preview-teleported="true"
                        />
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template v-slot="{ row }">
                        <el-button
                            type="warning"
                            size="default"
                            icon="ele-Edit"
                            @click="updateTrademark(row)"
                            v-has="'btn.Trademark.update'"
                            >修改</el-button
                        >

                        <el-popconfirm
                            title="你确定要删除我吗?"
                            @confirm="confirmDelete(row.id)"
                        >
                            <template #reference>
                                <el-button
                                    type="danger"
                                    size="default"
                                    icon="ele-Delete"
                                    v-has="'btn.Trademark.remove'"
                                    >删除</el-button
                                >
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                v-model:page-size="pageSize"
                :page-count="pageCount"
                :pager-count="5"
                :page-sizes="[3, 5, 7, 9]"
                v-model:current-page="currentPage"
                layout=" prev, pager, next, sizes"
            />
        </el-card>

        <!-- 添加或者修改的弹窗 -->
        <el-dialog
            v-model="dialogVisible"
            :title="trademarkData.id ? '修改品牌' : '添加品牌'"
        >
            <el-form
                label-width="120px"
                :rules="rules"
                ref="formEle"
                :model="trademarkData"
            >
                <el-form-item label="品牌名称" prop="tmName">
                    <el-input v-model="trademarkData.tmName" />
                </el-form-item>
                <el-form-item label="品牌LOGO" prop="logoUrl">
                    <el-upload
                        class="avatar-uploader"
                        action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                    >
                        <img
                            v-if="trademarkData.logoUrl"
                            :src="trademarkData.logoUrl"
                            class="avatar"
                        />
                        <el-icon v-else class="avatar-uploader-icon"
                            ><ele-Plus
                        /></el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="addOrUpdate">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
    name: 'Trademark',
});
</script>

<script setup lang="ts">
import { onMounted, ref, watch, reactive } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import {
    reqUpdateTrademark,
    reqAddTrademark,
    reqDeleteTrademark,
} from '@/api/trademark';
//引入品牌列表的数组的类型
import type { trademarkListType, trademarkItemType } from '@/api/trademark';
import type { UploadProps } from 'element-plus';
//获取trademark的store对象
import useTrademarkStore from '@/stores/trademark';
const trademarkStore = useTrademarkStore();

//首先模拟一个表格数据
const tabelData = ref<trademarkListType>([]);
//page的数据
//1. 每页条数
const pageSize = ref(3);
//2. 总页数
const pageCount = ref(0);
//3. 当前页码
const currentPage = ref(1);

//封装一个请求分页列表，并处理数据的函数
const initTrademark = async () => {
    try {
        await trademarkStore.getTrademark(currentPage.value, pageSize.value);
        tabelData.value = trademarkStore.trademarkList;
        pageCount.value = trademarkStore.pages;
    } catch (e: any) {
        ElMessage.error(e.message);
    }
};
//在mounted中发送请求获取trademark的数据
onMounted(() => {
    initTrademark();
});

//watch监听当前页码和每页条数 只要法神不过变化，则重新发送请求
watch([pageSize, currentPage], () => {
    initTrademark();
});

//弹窗控制显示隐藏的数据定义
const dialogVisible = ref(false);
//定义一个新增或者修改的品牌数据
const trademarkData = ref<trademarkItemType>({
    tmName: '',
    logoUrl: '',
});

//上传逻辑
//整体校验
const formEle = ref<FormInstance>();
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
    // console.log(response, uploadFile);
    trademarkData.value.logoUrl = response.data;
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!');
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!');
        return false;
    }
    return true;
};

//修改品牌的事件回调函数
const updateTrademark = (row: trademarkItemType) => {
    //每次打开弹窗先关闭之前的校验提示
    formEle.value?.clearValidate();
    dialogVisible.value = true;
    trademarkData.value = { ...row };
};

//新增品牌的事件回调函数
const addTrademark = () => {
    //每次打开弹窗先关闭之前的校验提示
    formEle.value?.clearValidate();

    trademarkData.value = {
        tmName: '',
        logoUrl: '',
    };
    dialogVisible.value = true;
};

//新增或者修改品牌的回调函数
const addOrUpdate = async () => {
    //整体校验(因为校验失败会返回失败的promise,所以我们需要进行异常处理)
    try {
        const re = await formEle.value?.validate();
        console.log(re);
        if (!re) {
            return;
        }
    } catch (e) {
        return;
    }

    try {
        //先根据trademarkData中的id判断当前是更新还是新增
        if (trademarkData.value.id) {
            await reqUpdateTrademark(trademarkData.value);
            ElMessage.success('更新成功');
        } else {
            await reqAddTrademark(trademarkData.value);
            ElMessage.success('新增成功');
        }
    } catch (e: any) {
        ElMessage.error(e.message);
    }
    //关闭弹窗
    dialogVisible.value = false;
    // 重新获取数据
    initTrademark();
};

//表单校验的规则定义
const rules = reactive<FormRules>({
    tmName: [{ required: true, message: '品牌名称不能为空', trigger: 'blur' }],
    logoUrl: [
        { required: true, message: '品牌的logo不能为空', trigger: 'blur' },
    ],
});

//删除某个品牌
/* const deleteTrademark = async (id: number) => {

}; */

const confirmDelete = async (id: number) => {
    try {
        await reqDeleteTrademark(id);
        // 重新获取数据
        initTrademark();
    } catch (e: any) {
        ElMessage.error(e.message);
    }
};
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
